<template>
  <section id="home" class="container mx-auto px-4 py-8 md:py-12">
    <div class="text-center mb-10">
      <h2 class="text-[clamp(1.8rem,4vw,2.8rem)] font-bold mb-4 text-shadow">
        把你的文字，变成<span class="text-primary">漫画</span>世界
      </h2>
      <p class="text-gray-600 max-w-2xl mx-auto text-lg">
        只需输入小说片段，AI将自动解析情节，生成符合风格的漫画分镜，让文字跃然纸上
      </p>
    </div>
    
    <!-- 主交互区 -->
    <div class="grid grid-cols-1 lg:grid-cols-5 gap-6">
      <!-- 左侧：输入与设置区 -->
      <div class="lg:col-span-2 bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-xl font-bold mb-4 flex items-center">
          <i class="fa fa-file-text-o text-primary mr-2"></i>输入小说片段
        </h3>
        
        <div class="mb-6">
          <textarea 
            v-model="novelText"
            class="w-full h-48 p-4 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all resize-none"
            placeholder="粘贴你的小说片段（建议500字以内），例如：
他站在雨中，伞沿滴落的水打湿了皮鞋，远处的钟楼敲响了十下..."
            @input="handleTextInput"
          ></textarea>
          <div class="flex justify-between mt-2 text-sm text-gray-500" :class="{ 'text-red-500': wordCount > 500 }">
            <span>{{ wordCount }}/500字</span>
            <button @click="loadExampleText" class="text-primary hover:underline">加载示例文本</button>
          </div>
        </div>
        
        <h3 class="text-xl font-bold mb-4 flex items-center">
          <i class="fa fa-sliders text-primary mr-2"></i>漫画风格设置
        </h3>
        
        <!-- 风格选择 -->
        <div class="mb-5">
          <label class="block text-sm font-medium mb-2">漫画风格</label>
          <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <button 
              @click="selectStyle('日系')"
              :class="activeStyle === '日系' ? 'bg-primary/10 border-2 border-primary' : 'bg-white border border-gray-300 hover:border-primary/50'"
              class="style-btn rounded-lg p-3 flex flex-col items-center"
            >
              <i :class="activeStyle === '日系' ? 'fa fa-star text-primary' : 'fa fa-star text-gray-500'" class="mb-1"></i>
              <span class="text-sm">日系</span>
            </button>
            <button 
              @click="selectStyle('欧美')"
              :class="activeStyle === '欧美' ? 'bg-primary/10 border-2 border-primary' : 'bg-white border border-gray-300 hover:border-primary/50'"
              class="style-btn rounded-lg p-3 flex flex-col items-center"
            >
              <i :class="activeStyle === '欧美' ? 'fa fa-globe text-primary' : 'fa fa-globe text-gray-500'" class="mb-1"></i>
              <span class="text-sm">欧美</span>
            </button>
            <button 
              @click="selectStyle('国风')"
              :class="activeStyle === '国风' ? 'bg-primary/10 border-2 border-primary' : 'bg-white border border-gray-300 hover:border-primary/50'"
              class="style-btn rounded-lg p-3 flex flex-col items-center"
            >
              <i :class="activeStyle === '国风' ? 'fa fa-pagelines text-primary' : 'fa fa-pagelines text-gray-500'" class="mb-1"></i>
              <span class="text-sm">国风</span>
            </button>
            <button 
              @click="selectStyle('Q版')"
              :class="activeStyle === 'Q版' ? 'bg-primary/10 border-2 border-primary' : 'bg-white border border-gray-300 hover:border-primary/50'"
              class="style-btn rounded-lg p-3 flex flex-col items-center"
            >
              <i :class="activeStyle === 'Q版' ? 'fa fa-smile-o text-primary' : 'fa fa-smile-o text-gray-500'" class="mb-1"></i>
              <span class="text-sm">Q版</span>
            </button>
          </div>
        </div>
        
        <!-- 画面基调 -->
        <div class="mb-5">
          <label class="block text-sm font-medium mb-2">画面基调</label>
          <div class="flex flex-wrap gap-2">
            <button 
              @click="selectTone('明亮')"
              :class="activeTone === '明亮' ? 'bg-dark text-white border border-dark' : 'bg-white border border-gray-300 hover:border-primary/50'"
              class="tone-btn px-3 py-1 rounded-full text-sm"
            >明亮</button>
            <button 
              @click="selectTone('暗黑')"
              :class="activeTone === '暗黑' ? 'bg-dark text-white border border-dark' : 'bg-white border border-gray-300 hover:border-primary/50'"
              class="tone-btn px-3 py-1 rounded-full text-sm"
            >暗黑</button>
            <button 
              @click="selectTone('复古')"
              :class="activeTone === '复古' ? 'bg-dark text-white border border-dark' : 'bg-white border border-gray-300 hover:border-primary/50'"
              class="tone-btn px-3 py-1 rounded-full text-sm"
            >复古</button>
            <button 
              @click="selectTone('科幻')"
              :class="activeTone === '科幻' ? 'bg-dark text-white border border-dark' : 'bg-white border border-gray-300 hover:border-primary/50'"
              class="tone-btn px-3 py-1 rounded-full text-sm"
            >科幻</button>
            <button 
              @click="selectTone('唯美')"
              :class="activeTone === '唯美' ? 'bg-dark text-white border border-dark' : 'bg-white border border-gray-300 hover:border-primary/50'"
              class="tone-btn px-3 py-1 rounded-full text-sm"
            >唯美</button>
          </div>
        </div>
        
        <!-- 角色偏好 -->
        <div class="mb-6">
          <label class="block text-sm font-medium mb-2">角色偏好（可选）</label>
          <div class="grid grid-cols-2 gap-3">
            <select class="border border-gray-300 rounded-lg p-2 focus:ring-2 focus:ring-primary/50 focus:border-primary">
              <option>自动识别</option>
              <option>少年</option>
              <option>少女</option>
              <option>成人</option>
              <option>老人</option>
            </select>
            <select class="border border-gray-300 rounded-lg p-2 focus:ring-2 focus:ring-primary/50 focus:border-primary">
              <option>默认发型</option>
              <option>短发</option>
              <option>长发</option>
              <option>卷发</option>
              <option>特殊发型</option>
            </select>
          </div>
        </div>
        
        <!-- 生成按钮 -->
        <button 
          @click="generateComic"
          class="w-full py-4 bg-secondary text-white rounded-xl font-bold text-lg shadow-lg hover:shadow-xl hover:bg-secondary/90 transition-all flex items-center justify-center gap-2"
        >
          <i class="fa fa-magic"></i>
          <span>生成漫画</span>
        </button>
        <p class="text-xs text-gray-500 text-center mt-2">生成可能需要30秒~2分钟，请耐心等待</p>
      </div>
      
      <!-- 右侧：预览区 -->
      <div class="lg:col-span-3 bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-xl font-bold mb-4 flex items-center">
          <i class="fa fa-image text-primary mr-2"></i>
          {{ previewState !== 'initial' ? '漫画预览' : '推荐样例' }}
        </h3>
        
        <!-- 初始状态：显示样例画廊 -->
        <div v-if="previewState === 'initial'">
          <div class="mb-6">
            <!-- 样例筛选 -->
            <div class="flex flex-wrap justify-center gap-3 mb-4">
              <button 
                @click="setGalleryFilter('全部作品')"
                :class="activeGalleryFilter === '全部作品' ? 'bg-primary text-white' : 'bg-gray-100 hover:bg-gray-200'"
                class="px-3 py-1 rounded-lg text-sm transition-colors"
              >全部作品</button>
              <button 
                @click="setGalleryFilter('日系风格')"
                :class="activeGalleryFilter === '日系风格' ? 'bg-primary text-white' : 'bg-gray-100 hover:bg-gray-200'"
                class="px-3 py-1 rounded-lg text-sm transition-colors"
              >日系风格</button>
              <button 
                @click="setGalleryFilter('国风风格')"
                :class="activeGalleryFilter === '国风风格' ? 'bg-primary text-white' : 'bg-gray-100 hover:bg-gray-200'"
                class="px-3 py-1 rounded-lg text-sm transition-colors"
              >国风风格</button>
              <button 
                @click="setGalleryFilter('科幻题材')"
                :class="activeGalleryFilter === '科幻题材' ? 'bg-primary text-white' : 'bg-gray-100 hover:bg-gray-200'"
                class="px-3 py-1 rounded-lg text-sm transition-colors"
              >科幻题材</button>
            </div>
            
            <!-- 样例展示网格 -->
            <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
              <GalleryItem 
                v-for="item in filteredGalleryItems" 
                :key="item.id"
                :item="item"
              />
            </div>
          </div>
          
          <div class="text-center text-sm text-gray-500">
            输入小说片段并设置风格，生成属于你的漫画
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div 
          id="preview-loading" 
          class="min-h-[500px] flex flex-col items-center justify-center border-2 border-dashed border-gray-300 rounded-lg p-6"
          v-if="previewState === 'loading'"
        >
          <div class="relative w-64 h-64 mb-6">
            <svg class="w-full h-full" viewBox="0 0 100 100">
              <rect x="10" y="10" width="30" height="30" fill="none" stroke="#6366f1" stroke-width="2" class="sketch-line"/>
              <rect x="60" y="10" width="30" height="30" fill="none" stroke="#6366f1" stroke-width="2" class="sketch-line" style="animation-delay: 0.2s"/>
              <rect x="10" y="60" width="30" height="30" fill="none" stroke="#6366f1" stroke-width="2" class="sketch-line" style="animation-delay: 0.4s"/>
              <rect x="60" y="60" width="30" height="30" fill="none" stroke="#6366f1" stroke-width="2" class="sketch-line" style="animation-delay: 0.6s"/>
            </svg>
            <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-primary">
              <i class="fa fa-pencil fa-lg fa-spin"></i>
            </div>
          </div>
          <h4 class="text-xl font-medium text-gray-700 mb-2">正在绘制漫画...</h4>
          <div class="w-full max-w-md h-2 bg-gray-200 rounded-full overflow-hidden">
            <div class="h-full bg-primary rounded-full w-1/3 animate-pulse-slow"></div>
          </div>
          <p class="text-gray-500 mt-4 text-center">AI正在解析文本并创作分镜，请稍候</p>
        </div>
        
        <!-- 结果展示 -->
        <div v-if="previewState === 'result'">
          <div class="comic-border bg-white rounded-lg p-1 mb-4">
            <!-- 漫画分镜网格 -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              <div 
                v-for="(frame, index) in generatedComicFrames" 
                :key="index"
                class="comic-frame relative bg-gray-50 p-2 rounded-lg shadow-sm cursor-pointer hover:shadow-md transition-shadow"
                @click="openFramePreview(frame, index)"
              >
                <img 
                  :src="frame.Url" 
                  :alt="`分镜 ${index + 1}: ${frame.Desc}`" 
                  class="w-full h-auto rounded object-cover aspect-[3/4]"
                >
                <div class="absolute bottom-2 left-2 right-2 bg-black/70 text-white p-2 rounded text-sm">
                  {{ frame.Desc }}
                </div>
                <div class="absolute top-2 left-2 bg-primary text-white text-xs py-1 px-2 rounded">
                  分镜 {{ index + 1 }}
                </div>
                <div class="absolute top-2 right-2 bg-white/90 text-primary text-xs py-1 px-2 rounded">
                  点击放大
                </div>
              </div>
            </div>
          </div>
          
          <!-- 操作按钮 -->
            <div class="flex flex-wrap gap-3 justify-center">
              <button class="px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 flex items-center gap-1" @click="() => previewState = 'initial'">
                <i class="fa fa-refresh"></i> 重新生成
              </button>
              <button class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 flex items-center gap-1" @click="downloadComic">
                <i class="fa fa-download"></i> 下载所有分镜
              </button>
            </div>
        </div>
      </div>
    </div>
    
    <!-- 图片预览模态框 -->
    <div 
      v-if="isImagePreviewOpen" 
      class="fixed inset-0 bg-black/80 z-50 flex items-center justify-center p-4"
      @click="closeFramePreview"
    >
      <div 
        class="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-auto p-4 relative"
        @click.stop
      >
        <!-- 关闭按钮 -->
        <button 
          class="absolute top-4 right-4 bg-black/50 text-white p-2 rounded-full hover:bg-black/70 transition-colors"
          @click="closeFramePreview"
        >
          <i class="fa fa-times"></i>
        </button>
        
        <!-- 预览内容 -->
        <div class="flex flex-col items-center">
          <h3 class="text-xl font-bold mb-4">分镜 {{ previewIndex + 1 }}</h3>
          <div class="max-w-full max-h-[70vh] mb-6">
            <img 
              :src="previewImage?.Url" 
              :alt="`分镜 ${previewIndex + 1}: ${previewImage?.Desc}`" 
              class="max-w-full max-h-full object-contain"
            >
          </div>
          <div class="text-gray-700 mb-6 w-full max-w-2xl text-center">
            {{ previewImage?.Desc }}
          </div>
          <button 
            class="px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors flex items-center gap-2"
            @click="downloadFrame(previewImage, previewIndex)"
          >
            <i class="fa fa-download"></i> 下载此分镜
          </button>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import GalleryItem from './GalleryItem.vue'
import api from '../utils/api.js'

const router = useRouter()

// 文本输入相关
const novelText = ref('')
const wordCount = ref(0)

// 风格设置相关
const activeStyle = ref('日系')
const activeTone = ref('暗黑')

// 预览状态管理
const previewState = ref('initial') // initial, loading, result
// 生成的漫画分镜数组
const generatedComicFrames = ref([])

// 画廊样例相关
const activeGalleryFilter = ref("全部作品")
const galleryItems = ref([
  { id: 1, title: "林间奇遇", category: "国风 · 奇幻", image: "https://picsum.photos/id/1024/400/500", style: "国风风格" },
  { id: 2, title: "都市夜景", category: "日系 · 日常", image: "https://picsum.photos/id/1027/400/500", style: "日系风格" },
  { id: 3, title: "太空站", category: "科幻 · 未来", image: "https://picsum.photos/id/1028/400/500", style: "科幻题材" },
  { id: 4, title: "古风小镇", category: "国风 · 生活", image: "https://picsum.photos/id/1039/400/500", style: "国风风格" },
  { id: 5, title: "校园时光", category: "日系 · 青春", image: "https://picsum.photos/id/1040/400/500", style: "日系风格" },
  { id: 6, title: "星际旅行", category: "科幻 · 冒险", image: "https://picsum.photos/id/1041/400/500", style: "科幻题材" }
])

// 处理文本输入
const handleTextInput = () => {
  let value = novelText.value
  if (value.length > 500) {
    novelText.value = value.substring(0, 500)
  }
  wordCount.value = novelText.value.length
}

// 加载示例文本
const loadExampleText = () => {
  novelText.value = "他站在雨中，伞沿滴落的水打湿了皮鞋，远处的钟楼敲响了十下。夜色渐浓，街道上的行人寥寥无几，只有路灯在雨雾中散发着朦胧的光晕。他紧了紧衣领，转身走向那条没有路灯的小巷，仿佛那里有什么在等待着他。"
  wordCount.value = novelText.value.length
}

// 选择风格
const selectStyle = (style) => {
  activeStyle.value = style
}

// 选择基调
const selectTone = (tone) => {
  activeTone.value = tone
}

// 生成漫画
const generateComic = async () => {
  // 检查是否登录和认证token是否有效
  const userInfo = localStorage.getItem('userInfo')
  const authToken = localStorage.getItem('authToken')
  if (!userInfo || !authToken) {
    // 保存当前用户的输入和选择到localStorage
    const userSelections = {
      novelText: novelText.value,
      activeStyle: activeStyle.value,
      activeTone: activeTone.value
    }
    localStorage.setItem('pendingComicSelections', JSON.stringify(userSelections))
    
    // 跳转到登录页
    router.push('/login')
    return
  }
  
  if (!novelText.value.trim()) {
    alert('请输入小说片段')
    return
  }
  
  previewState.value = 'loading'
  
  try {
    // 构建请求数据，符合接口规范
    const requestData = {
      text: novelText.value.trim(),
      style: activeStyle.value,
      tone: activeTone.value,
      // 角色相关信息，默认保持空字符串以便后端自动识别
      appearance: '', // 可选，空字符串表示自动识别
      gender: '' // 可选，空字符串表示自动识别
    }
    
    console.log('准备发送请求到后端:', requestData)
    
    // 发送请求到后端
    const response = await api.post('/generate/draw', requestData)
    
    console.log('收到后端响应:', response)
    
    // 检查响应状态
    if (response.code === 0) {
      // 成功 - 显示结果
      previewState.value = 'result'
      // 保存后端返回的分镜数据，清理URL中的反引号
      generatedComicFrames.value = response.data.map(frame => ({
        ...frame,
        Url: frame.Url.replace(/[`]/g, '').trim()
      }))
      console.log('生成成功，分镜数量:', generatedComicFrames.value.length)
    } else if (response.code === 4) {
      // 业务错误
      alert(`生成失败：${response.msg || '参数错误'}`)
      previewState.value = 'initial'
    } else if (response.code === 5) {
      // 系统错误 - 但检查是否有返回分镜数据
      if (response.data && Array.isArray(response.data) && response.data.length > 0) {
        // 如果有分镜数据，仍然显示结果
        previewState.value = 'result'
        generatedComicFrames.value = response.data.map(frame => ({
          ...frame,
          Url: frame.Url.replace(/[`]/g, '').trim()
        }))
        console.log('系统返回了分镜数据，尽管状态码为5:', generatedComicFrames.value.length)
      } else {
        // 没有图片数据时显示错误
        alert('系统错误，请稍后重试')
        previewState.value = 'initial'
      }
    } else {
      // 其他错误
      alert(`生成失败：${response.msg || '未知错误'}`)
      previewState.value = 'initial'
    }
  } catch (error) {
    console.error('API请求失败详情:', error)
    console.error('错误堆栈:', error.stack)
    alert(`网络错误：${error.message || '请求发送失败'}`)
    previewState.value = 'initial'
  }
}

// 预览相关状态
const previewImage = ref(null)
const previewIndex = ref(-1)
const isImagePreviewOpen = ref(false)

// 打开图片预览
const openFramePreview = (frame, index) => {
  if (!frame || !frame.Url) {
    alert('分镜图片无效');
    return;
  }
  
  previewImage.value = frame
  previewIndex.value = index
  isImagePreviewOpen.value = true
}

// 关闭图片预览
const closeFramePreview = () => {
  isImagePreviewOpen.value = false
  previewImage.value = null
  previewIndex.value = -1
}

// 下载单个分镜图片
const downloadFrame = (frame, index) => {
  if (!frame || !frame.Url) {
    alert('分镜图片无效');
    return;
  }
  
  try {
    const link = document.createElement('a');
    link.href = frame.Url;
    link.download = `comic_frame_${index + 1}_${new Date().getTime()}.png`;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    
    setTimeout(() => {
      document.body.removeChild(link);
    }, 100);
    
    console.log(`分镜 ${index + 1} 下载已触发`);
  } catch (error) {
    console.error(`下载分镜 ${index + 1} 失败:`, error);
    alert('下载图片失败，请稍后重试');
  }
}

// 下载所有分镜
const downloadComic = async () => {
  if (generatedComicFrames.value.length === 0) {
    alert('没有可下载的漫画分镜');
    return;
  }
  
  try {
    // 逐个下载所有分镜
    for (let i = 0; i < generatedComicFrames.value.length; i++) {
      const frame = generatedComicFrames.value[i];
      if (frame && frame.Url) {
        await downloadFrame(frame, i);
        // 添加延迟避免浏览器限制
        if (i < generatedComicFrames.value.length - 1) {
          await new Promise(resolve => setTimeout(resolve, 500));
        }
      }
    }
    
    console.log('所有分镜下载完成');
  } catch (error) {
    console.error('下载漫画失败:', error);
    alert('下载漫画失败，请稍后重试');
  }
}

// 画廊筛选
const setGalleryFilter = (filter) => {
  activeGalleryFilter.value = filter
}

// 根据筛选条件过滤样例
const filteredGalleryItems = computed(() => {
  if (activeGalleryFilter.value === '全部作品') {
    return galleryItems.value
  }
  return galleryItems.value.filter(item => item.style === activeGalleryFilter.value)
})

// 检查是否有待恢复的选择
onMounted(() => {
  const savedSelections = localStorage.getItem('pendingComicSelections')
  if (savedSelections && localStorage.getItem('userInfo')) {
    try {
      const selections = JSON.parse(savedSelections)
      // 恢复用户之前的选择
      if (selections.novelText) novelText.value = selections.novelText
      if (selections.activeStyle) activeStyle.value = selections.activeStyle
      if (selections.activeTone) activeTone.value = selections.activeTone
      // 更新字数统计
      wordCount.value = novelText.value.length
      // 清除保存的选择，避免重复恢复
      localStorage.removeItem('pendingComicSelections')
    } catch (e) {
      console.error('解析保存的选择失败:', e)
    }
  }
})
</script>